<?php

namespace support\middleware;

use app\common\Sign;
use app\model\MenuModel;
use app\model\RoleMenuModel;
use app\model\UserModel;
use app\model\UserRoleModel;
use support\bootstrap\Container;
use Doctrine\Common\Annotations\AnnotationReader;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AuthorizeControl implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        $method = new \ReflectionMethod($request->controller,$request->action);
        $reader = new AnnotationReader();
        foreach ($reader->getMethodAnnotations($method) as $annotation) {
            if (strlen($annotation->action) > 0) {
                $role_id_arr = UserRoleModel::where(['user_id' => $request->user_id])->column('role_id');
                if(!in_array(1,$role_id_arr)){//排除超级管理员
                    $menu_id_arr = RoleMenuModel::where([['role_id','in',$role_id_arr]])->column('menu_id');
                    $can = MenuModel::where([['menu_id','in',$menu_id_arr],['authority','=',$annotation->action]])->find();
                    if(!$can){
                        return error('1', '权限不足');
                    }
                }
            }
        }
        $response = $next($request);

        return $response;
    }
}